package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class HttpServletRequest {
    private Socket socket;
    private Map<String , String> headers = new HashMap<>();
    private String method;
    private String uri;
    private String protocol;
    private String requestURI;//保存uri中?左侧的内容，如果uri中没有"?"则内容与uri一致
    private String queryString;//保存uri中"?"右侧内容，即：参数部分
    //用来保存客户端传递过来的每一组参数
    private Map<String , String> parameters = new HashMap<>();

    public HttpServletRequest(Socket socket) throws IOException, EmptyRequestException {
        this.socket = socket;
        //1.1解析请求行
        parseRequestLine();
        //1.2解析消息头
        parseHeaders();
        //1.3解析消息正文
        parseContent();
    }




    private String readLine() throws IOException {

        InputStream in = socket.getInputStream();//创建输入流读取请求数据

        StringBuilder builder = new StringBuilder();
        int d;
        char pre = 'a', cur = 'a';//用两个字符变量，分别代表当前字符和上一个字符
        while ((d = in.read())!=-1){
            pre = (char)d;//将读取到的字节转换为字符赋值给pre
            if (cur==13&&pre==10){//当上一个字符等于回车，当前字符等于换行时，循环结束
                break;
            }
            builder.append(pre);//将读取的字符拼接到builder中
            cur = pre;//在进行下一次读取前将当前字符赋值给cur，让cur作为上一次读取的字符
        }
        return builder.toString().trim();//转换为字符串类型并去两边的空字符
    }

    private void parseRequestLine() throws IOException, EmptyRequestException {
        String line =readLine();

        if (line.isEmpty()){//如果请求行为空字符串，则说明为空请求
            throw new EmptyRequestException();
        }
        System.out.println(line);
        String[] array = line.split("\\s");
        //将解析行的内容拆分成三部分，分别赋值给三个变量
        method = array[0];
        uri = array[1];
        protocol = array[2];

        //进一步解析uri
        parseUri();

        System.out.println("method:"+method);
        System.out.println("uri:"+uri);
        System.out.println("protocol:"+protocol);
    }

    /**
     * 进一步解析uri
     */
    private void parseUri(){
        String[] data = uri.split("\\?");
        requestURI = data[0];
        if (data.length>1){
            queryString = data[1];
            parseParameter(queryString);
        }

//        if (uri.contains("?")){
//            requestURI = uri.substring(0,uri.indexOf("?"));
//            queryString = uri.substring(uri.indexOf("?")+1);
//            String[] array = queryString.split("&");
//            for (int i = 0; i < array.length; i++) {
//                String[] array1 = array[i].split("=");
//                if (array1.length <= 1) {
//                    parameters.put(array1[0], null);
//                } else {
//                    parameters.put(array1[0], array1[1]);
//                }
////                String key = array[i].substring(0,array[i].indexOf("="));
////                String value = array[i].substring(array[i].indexOf("=")+1);
////                if (value.isEmpty()){
////                    parameters.put(key , null);
////                }else{
////                  parameters.put(key ,value);
//            //    }
//            }
//        }


        System.out.println("requestURI:"+requestURI);
        System.out.println("queryString:"+queryString);
        System.out.println("parameters:"+parameters);
    }


    private void parseHeaders() throws IOException {
        String line;
        while (!(line = readLine()).isEmpty()){
            String[] array = line.split(":\\s");
            headers.put(array[0].toLowerCase(),array[1]);
            System.out.println("消息头:"+line);
        }
        System.out.println(headers);
    }

    private void parseContent() throws IOException {
        //当一个请求的请求方式为POST时，则说明应当会包含消息正文
        if ("post".equalsIgnoreCase(method)){
            //消息头中是否含有Content-Length
            if (headers.containsKey("content-length")){
                int contentLength = Integer.parseInt(
                        headers.get("content-length")
                );
                System.out.println(">>>>>>>"+contentLength);
                //根据Content-Length指定的长度创建字节数组
                byte[] data = new byte[contentLength];
                InputStream in = socket.getInputStream();
                //将正文内容块读进data数组中备用
                in.read(data);

                //根据消息头Content-Type判断正文类型，并进行对应的解析
                if (headers.containsKey("content-type")){
                    String contentType = headers.get("content-type");
                    System.out.println("==========="+contentType);
                    //如果正文类型为form表单提交数据
                    if ("application/x-www-form-urlencoded".equals(contentType)){
                        String line = new String(data, StandardCharsets.ISO_8859_1);
                        System.out.println("正文内容=====:"+line);
                        parseParameter(line);

                    }//后期可扩展else if (xxx/xxx){}

                }


            }

        }
    }

    /**
     * 解析参数。参数的格式应当是:name1=value&name2=value2
     * @param line
     */
    private void parseParameter(String line){
        try {
            line = URLDecoder.decode(line,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String[] data = line.split("&");
        for (String para : data) {
            String[] paras = para.split("=");
            parameters.put(paras[0],paras.length>1?paras[1]:null);
        }
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getHeader(String name){
        return headers.get(name.toLowerCase());
    }

    public String getRequestURI() {
        return requestURI;
    }

    public String getQueryString() {
        return queryString;
    }

    /**
     * 根据参数名获取对应的参数值
     * @param name
     * @return
     */
    public String getParameter(String name){
        return parameters.get(name);
    }
}
